package com.crrc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crrc.model.entity.QueryCondition;
import com.crrc.model.entity.QueryConditions;
import com.crrc.utils.FieldUtils;
import com.crrc.utils.PageRequest;
import com.crrc.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

public abstract class BaseController<T, ID extends Serializable, M extends BaseMapper<T>, S extends ServiceImpl<M, T>> {

    @Autowired
    protected S service;

    @GetMapping("/getAll")
    public Result getAll() {
        try {
            List<T> entities = service.list();
            return new Result(200, "数据查询成功", entities);
        } catch (NullPointerException e) {
            return new Result(401, "对象为空: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            return new Result(402, "非法参数: " + e.getMessage());
        } catch (Exception e) {
            return new Result(400, "未知错误: " + e.getMessage());
        }
    }

    @GetMapping("/getOne")
    public Result getById(@RequestParam ID id) {
        try {
            T entity = service.getById(id);
            return new Result(200, "数据查询成功", entity);
        } catch (NullPointerException e) {
            return new Result(401, "对象为空: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            return new Result(402, "非法参数: " + e.getMessage());
        } catch (Exception e) {
            return new Result(400, "未知错误: " + e.getMessage());
        }
    }

    @PostMapping("/insertOne")
    public Result create(@RequestBody T entity) {
        try {
            if (service.save(entity)){
                return new Result(200, "数据插入成功");
            }
            return new Result(400, "数据插入失败", "插入操作未成功");
        } catch (NullPointerException e) {
            return new Result(401, "对象为空: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            return new Result(402, "非法参数: " + e.getMessage());
        } catch (Exception e) {
            return new Result(400, "未知错误: " + e.getMessage());
        }
    }

    @PostMapping("/insertBatch")
    public Result insertBatch(@RequestBody List<T> entities) {
        try {
            if (service.saveBatch(entities)) {
                return new Result(200, "批量数据插入成功");
            }
            return new Result(400, "批量数据插入失败", "插入操作未成功");
        } catch (NullPointerException e) {
            return new Result(401, "对象为空: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            return new Result(402, "非法参数: " + e.getMessage());
        } catch (Exception e) {
            return new Result(400, "未知错误: " + e.getMessage());
        }
    }

    @PostMapping("/updateOne")
    public Result update(@RequestBody T entity) {
        try {
            if (service.updateById(entity)) {
                return new Result(200, "数据更新成功");
            }
            return new Result(400, "数据更新失败", "更新操作未成功");
        } catch (NullPointerException e) {
            return new Result(401, "对象为空: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            return new Result(402, "非法参数: " + e.getMessage());
        } catch (Exception e) {
            return new Result(400, "未知错误: " + e.getMessage());
        }
    }

    @PostMapping("/updateBatch")
    public Result updateBatch(@RequestBody List<T> entities) {
        try {
            if (service.saveOrUpdateBatch(entities)) {
                return new Result(200, "批量数据更新成功");
            }
            return new Result(400, "批量数据更新失败", "更新操作未成功");
        } catch (NullPointerException e) {
            return new Result(401, "对象为空: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            return new Result(402, "非法参数: " + e.getMessage());
        } catch (Exception e) {
            return new Result(400, "未知错误: " + e.getMessage());
        }
    }

    @DeleteMapping("/deleteOne")
    public Result delete(@RequestParam ID id) {
        try {
            if (service.removeById(id)) {
                return new Result(200, "数据删除成功");
            }
            return new Result(400, "数据删除失败", "删除操作未成功");
        } catch (NullPointerException e) {
            return new Result(401, "对象为空: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            return new Result(402, "非法参数: " + e.getMessage());
        } catch (Exception e) {
            return new Result(400, "未知错误: " + e.getMessage());
        }
    }

    @DeleteMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam List<ID> ids) {
        try {
            if (service.removeByIds(ids)) {
                return new Result(200, "批量数据删除成功");
            }
            return new Result(400, "批量数据删除失败", "删除操作未成功");
        } catch (NullPointerException e) {
            return new Result(401, "对象为空: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            return new Result(402, "非法参数: " + e.getMessage());
        } catch (Exception e) {
            return new Result(400, "未知错误: " + e.getMessage());
        }
    }

    @PostMapping("/queryByCondition")
    public Result query(@RequestBody Map<String, Object> queryConditions) {
        try {
            QueryWrapper<T> queryWrapper = new QueryWrapper<>();
            for (Map.Entry<String, Object> entry : queryConditions.entrySet()) {
                String field = entry.getKey();
                Object value = entry.getValue();
                String mappedField = FieldUtils.camelToSnake(field);
                queryWrapper.eq(mappedField, value);
            }
            List<T> entities = service.list(queryWrapper);
            return new Result(200, "数据查询成功", entities);
        } catch (NullPointerException e) {
            return new Result(401, "对象为空: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            return new Result(402, "非法参数: " + e.getMessage());
        } catch (Exception e) {
            return new Result(400, "未知错误: " + e.getMessage());
        }
    }

    @PostMapping("/queryByMoreConditions")
    public Result query(@RequestBody QueryConditions queryConditions) {
        try {
            QueryWrapper<T> queryWrapper = new QueryWrapper<>();
            for (QueryCondition condition : queryConditions.getConditions()) {
                switch (condition.getOperator().toLowerCase()) {
                    case "eq":
                        queryWrapper.eq(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                        break;
                    case "ne":
                        queryWrapper.ne(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                        break;
                    case "like":
                        queryWrapper.like(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                        break;
                    case "notlike":
                        queryWrapper.notLike(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                        break;
                    case "gt":
                        queryWrapper.gt(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                        break;
                    case "ge":
                        queryWrapper.ge(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                        break;
                    case "lt":
                        queryWrapper.lt(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                        break;
                    case "le":
                        queryWrapper.le(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                        break;
                    case "in":
                        queryWrapper.in(FieldUtils.camelToSnake(condition.getField()), (List<?>) condition.getValue());
                        break;
                    case "notin":
                        queryWrapper.notIn(FieldUtils.camelToSnake(condition.getField()), (List<?>) condition.getValue());
                        break;
                    case "isnull":
                        queryWrapper.isNull(FieldUtils.camelToSnake(condition.getField()));
                        break;
                    case "isnotnull":
                        queryWrapper.isNotNull(FieldUtils.camelToSnake(condition.getField()));
                        break;
                    default:
                        throw new IllegalArgumentException("Unsupported operator: " + condition.getOperator());
                }
            }
            List<T> entities = service.list(queryWrapper);
            return new Result(200, "数据查询成功", entities);
        } catch (NullPointerException e) {
            return new Result(401, "对象为空: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            return new Result(402, "非法参数: " + e.getMessage());
        } catch (Exception e) {
            return new Result(400, "未知错误: " + e.getMessage());
        }
    }

    @PostMapping("/deleteByCondition")
    public Result delete(@RequestBody Map<String, Object> queryConditions) {
        try {
            QueryWrapper<T> queryWrapper = new QueryWrapper<>();
            for (Map.Entry<String, Object> entry : queryConditions.entrySet()) {
                String field = entry.getKey();
                Object value = entry.getValue();
                String mappedField = FieldUtils.camelToSnake(field);
                queryWrapper.eq(mappedField, value);
            }
            if (service.remove(queryWrapper)) {
                return new Result(200, "批量数据删除成功");
            }
            return new Result(400, "批量数据删除失败", "删除操作未成功");
        } catch (NullPointerException e) {
            return new Result(401, "对象为空: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            return new Result(402, "非法参数: " + e.getMessage());
        } catch (Exception e) {
            return new Result(400, "未知错误: " + e.getMessage());
        }
    }

    @PostMapping("/deleteByMoreConditions")
    public Result delete(@RequestBody QueryConditions queryConditions) {
        try {
            QueryWrapper<T> queryWrapper = new QueryWrapper<>();
            for (QueryCondition condition : queryConditions.getConditions()) {
                switch (condition.getOperator().toLowerCase()) {
                    case "eq":
                        queryWrapper.eq(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                        break;
                    case "ne":
                        queryWrapper.ne(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                        break;
                    case "like":
                        queryWrapper.like(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                        break;
                    case "notlike":
                        queryWrapper.notLike(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                        break;
                    case "gt":
                        queryWrapper.gt(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                        break;
                    case "ge":
                        queryWrapper.ge(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                        break;
                    case "lt":
                        queryWrapper.lt(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                        break;
                    case "le":
                        queryWrapper.le(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                        break;
                    case "in":
                        queryWrapper.in(FieldUtils.camelToSnake(condition.getField()), (List<?>) condition.getValue());
                        break;
                    case "notin":
                        queryWrapper.notIn(FieldUtils.camelToSnake(condition.getField()), (List<?>) condition.getValue());
                        break;
                    case "isnull":
                        queryWrapper.isNull(FieldUtils.camelToSnake(condition.getField()));
                        break;
                    case "isnotnull":
                        queryWrapper.isNotNull(FieldUtils.camelToSnake(condition.getField()));
                        break;
                    default:
                        throw new IllegalArgumentException("Unsupported operator: " + condition.getOperator());
                }
            }
            if (service.remove(queryWrapper)) {
                return new Result(200, "批量数据删除成功");
            }
            return new Result(400, "批量数据删除失败", "删除操作未成功");
        } catch (NullPointerException e) {
            return new Result(401, "对象为空: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            return new Result(402, "非法参数: " + e.getMessage());
        } catch (Exception e) {
            return new Result(400, "未知错误: " + e.getMessage());
        }
    }

    @PostMapping("/queryPage")
    public Result queryPage(@RequestBody Map<String, Object> pageRequest) {
        try {
            Integer pageNum = (Integer) pageRequest.get("page");
            Integer pageSize = (Integer) pageRequest.get("size");
            if (pageNum == null||pageSize == null){
                return new Result(402,"参数page和size不能为空");
            }
            QueryWrapper<T> queryWrapper = new QueryWrapper<>();
            for (Map.Entry<String, Object> entry : pageRequest.entrySet()) {
                String field = entry.getKey();
                if ("page".equals(field) || "size".equals(field)) {
                    continue;
                }
                Object value = entry.getValue();
                String mappedField = FieldUtils.camelToSnake(field);
                queryWrapper.eq(mappedField, value);
            }
            Page<T> page = new Page<>(pageNum, pageSize);
            IPage<T> pageResult = service.page(page, queryWrapper);
            return new Result(200, "分页查询成功", pageResult);
        } catch (NullPointerException e) {
            return new Result(401, "对象为空: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            return new Result(402, "非法参数: " + e.getMessage());
        } catch (Exception e) {
            return new Result(400, "未知错误: " + e.getMessage());
        }
    }

    @PostMapping("/queryPageByMoreConditions")
    public Result queryPageByMoreConditions(@RequestBody PageRequest pageRequest) {
        try {
            QueryWrapper<T> queryWrapper = new QueryWrapper<>();
            if (pageRequest.getQueryConditions() != null) {
                for (QueryCondition condition : pageRequest.getQueryConditions().getConditions()) {
                    switch (condition.getOperator().toLowerCase()) {
                        case "eq":
                            queryWrapper.eq(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                            break;
                        case "ne":
                            queryWrapper.ne(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                            break;
                        case "like":
                            queryWrapper.like(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                            break;
                        case "notlike":
                            queryWrapper.notLike(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                            break;
                        case "gt":
                            queryWrapper.gt(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                            break;
                        case "ge":
                            queryWrapper.ge(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                            break;
                        case "lt":
                            queryWrapper.lt(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                            break;
                        case "le":
                            queryWrapper.le(FieldUtils.camelToSnake(condition.getField()), condition.getValue());
                            break;
                        case "in":
                            queryWrapper.in(FieldUtils.camelToSnake(condition.getField()), (List<?>) condition.getValue());
                            break;
                        case "notin":
                            queryWrapper.notIn(FieldUtils.camelToSnake(condition.getField()), (List<?>) condition.getValue());
                            break;
                        case "isnull":
                            queryWrapper.isNull(FieldUtils.camelToSnake(condition.getField()));
                            break;
                        case "isnotnull":
                            queryWrapper.isNotNull(FieldUtils.camelToSnake(condition.getField()));
                            break;
                        default:
                            throw new IllegalArgumentException("Unsupported operator: " + condition.getOperator());
                    }
                }
            }
            Page<T> page = new Page<>(pageRequest.getPage(), pageRequest.getSize());
            IPage<T> pageResult = service.page(page, queryWrapper);
            return new Result(200, "分页查询成功", pageResult);
        } catch (NullPointerException e) {
            return new Result(401, "对象为空: " + e.getMessage());
        } catch (IllegalArgumentException e) {
            return new Result(402, "非法参数: " + e.getMessage());
        } catch (Exception e) {
            return new Result(400, "未知错误: " + e.getMessage());
        }
        }
}
